package com.srwl.mytx.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.ReceivedForwardRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.RPTitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReceivedForwardRecordActivity extends AppCompatActivity {
    private static final String TAG = "ReceivedForwardRecordAc";
    private RecyclerView rv_forwardRecord;
    private ReceivedForwardRecordAdapter adapter;
    private ProgressBar progressBar;
    private RPTitleBar titleBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private ImageView iv_error;
    private List<Forward> forwardList = new ArrayList<>();
    private int page = 1;
    private final int SIZE = 10;
    private Boolean hasNextPage = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_received_forward_record);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.rp_top_red_color));
        rv_forwardRecord = findViewById(R.id.rv_forward_record);
        progressBar = findViewById(R.id.progress_bar);
        initTitleBar();
        initRefreshLayout();
        iv_error = findViewById(R.id.iv_error);
        adapter = new ReceivedForwardRecordAdapter(ReceivedForwardRecordActivity.this, forwardList);
        rv_forwardRecord.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rv_forwardRecord.setAdapter(adapter);
        loadForwardData();
    }

    private void initTitleBar() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setSubTitleVisibility(View.GONE);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initRefreshLayout() {
        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableOverScroll(false);
        // refreshLayout.setDisableRefresh(true);
        //  refreshLayout.setEnableHeaderDrawerStyle(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
            @Override
            public void onScroll(View content, float delta) {

                rv_forwardRecord.scrollBy(0, (int) delta);
            }
        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                forwardList.clear();
                page = 1;
                loadForwardData();
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadForwardData();
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    private void loadForwardData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (refreshLayout != null) refreshLayout.refreshComplete();
            Toast.makeText(this, getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .loadForwardRecords(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }
                        refreshLayout.refreshComplete();
                        CommonResult result = response.body();

                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (page == 1) {
                                iv_error.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (page == 1) {
                                iv_error.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        pageInfo.getInteger("total");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(ReceivedForwardRecordActivity.this)), 2000);
                        }
                        List<Forward> forwards = pageInfo.getJSONArray("list").toJavaList(Forward.class);
                        if (page == 1 && (forwards == null || forwards.size() == 0)) {
                            iv_error.setVisibility(View.VISIBLE);

                        } else {
                            if (iv_error.isShown()) {
                                iv_error.setVisibility(View.GONE);
                            }
                            forwardList.addAll(forwards);
                            adapter.notifyDataSetChanged();
                        }
                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        refreshLayout.refreshComplete();
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (page == 1) {
                            iv_error.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }
}
